﻿using Common.Dto;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;

namespace Common.Filter;

public class ControllerExceptionFilter : IAsyncExceptionFilter
{
    private readonly ILogger<ControllerExceptionFilter> _logger;

    public ControllerExceptionFilter(ILogger<ControllerExceptionFilter> logger)
    {
        _logger = logger;
    }

    public Task OnExceptionAsync(ExceptionContext context)
    {
        // throw new NotImplementedException();
        if (!context.ExceptionHandled)
        {
            context.Result = new ObjectResult(Result.Failure(context.Exception.Message))
            {
                StatusCode = 500,
                ContentTypes = { "application/json" }
            };
            
            _logger.LogError(context.Exception, "catch exception in filter");
        }

        context.ExceptionHandled = true;
        return Task.CompletedTask;
    }
}